
package com.schoolai.auth.service;

import com.schoolai.entity.jpa.SysMenu;
import com.schoolai.entity.jpa.SysUser;
import com.schoolai.feign.system.IFeignSchoolSystemController;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * Copyright(C),2019-2025，XX公司
 * FileName:MyUserDetailsService
 * Author:
 * 创建时间：2025/10/16 14:08
 * Description:
 * History:
 * <auth>        <time>       <version>       <desc>
 * 作者          修改时间       版本号         描述
 */


@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    IFeignSchoolSystemController feignSchoolSystemController;
    @Override

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 1. 判断用户名是否为空
        if(StringUtils.isEmpty(username)) {
            throw new BadCredentialsException("用户名不能为空");
        }
        // 2. 通过用户名查询数据库中的用户信息
        SysUser sysUser = feignSchoolSystemController.loadUserByUsername(username);
        if(sysUser == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        // 拥有的权限信息
        List<SysMenu> menuList = new ArrayList<>();
        sysUser.getSysRoleList().forEach(role -> {
            role.getSysMenuList().forEach(menu -> {
                menuList.add(menu);
            });
        });

        // 4. 封装权限信息（权限标识符code）
        List<GrantedAuthority> authorities = null;
        if(CollectionUtils.isNotEmpty(menuList)) {
            authorities = new ArrayList<>();
            for(SysMenu menu: menuList) {
                // 权限标识
                String code = menu.getCode();
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }
        // 5. 构建UserDetails接口的实现类JwtUser对象
        JwtUser jwtUser = new JwtUser(
                sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(),
                sysUser.getNickName(), sysUser.getImageUrl(), sysUser.getMobile(),
                sysUser.getEmail(),
                sysUser.getIsAccountNonExpired(), sysUser.getIsAccountNonLocked(),
                sysUser.getIsCredentialsNonExpired(), sysUser.getIsEnabled(),
                authorities );
        return jwtUser;
    }
}

